#!/usr/bin/env python3


"""repo_patch_fix
Usage:
	repo_patch_fix.py -h | --help
	repo_patch_fix.py -p PREFIX [-f FILE] [-d FOLDER]

Options:
	-h --help  show this message
	-p PREFIX  the prefix you need to add for fix
	-f FILE  the patch file you want to fix
	-d FOLDER  the directory in which all file will be fixed, fixed file will loated 'fixed'
"""
from docopt import docopt
from pathlib import Path
from pathlib import Path
import os


def fix_repo_file(fn, fix='', fout=''):
    """ 将从repo中导出的patch转换成大git能识别的文件
    fn 要修复的文件路径
    fix 要增加的前缀
    fout 输出文件路径
    """
    with open(fn) as fp:
        lines = fp.readlines()
    leaders = ('--- a', '+++ b')
    for i, line in enumerate(lines):
        for leader in leaders:
            if line.startswith(leader):
                lines[i] = f'{leader}/{fix}{line[len(leader):]}'
        if line.startswith('diff --git'):
            lines[i] = line.replace(' a/', f' a/{fix}/').replace(' b/', f' b/{fix}/')
    fout = fout if fout else f'{fn}.fix'
    with open(fout, 'w') as fp:
        fp.write(''.join(lines))


def fix_repo(folder, fix=''):
    """ 修改folder目录中的全部patch文件，并输出到$(folder)-fix目录中
    """
    out_folder = folder/'fixed'
    if not out_folder.exists():
        out_folder.mkdir()
    for f in os.listdir(folder):
        if f == 'fixed': continue
        print(f)
        fix_repo_file(folder/f, fix, out_folder/f)


def main(args):
	print(args)
	prefix = args.get("-p")
	if not prefix:
		raise ValueError("PREFIX must be assigned")
	# prefix should not endswith '/'
	if prefix.endswith("/"):
		prefix = prefix[:-1]

	file = args.get("-f")
	if file:
		file = Path(file)
		if not file.exists():
			raise ValueError(f"{file} not a regular file")
		fix_repo_file(file, fix=prefix)

	folder = args.get("-d")
	if folder:
		folder = Path(folder)
		if not folder.is_dir():
			raise ValueError(f"{folder} not a directory")
		fix_repo(folder, fix=prefix)


if __name__ == '__main__':
	arguments = docopt(__doc__, version='UserManage 2.0')
	main(arguments)
